package org.jvnet.hudson.client_demo;

import idv.arthur.widgets.Widgets;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jConfi {

	static Document document = null;

	public static void main(String[] args) {
		try {
			traverse();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	

	private static void traverse() throws Exception {
        String urlStr = "http://10.144.97.100:8080/jenkins/job/EJBModule/config.xml";
        //String urlStr = "http://10.144.136.48:8080/jenkins/job/DPS/config.xml";
        Widgets wid = new Widgets();
        Map<String,Object> map = new HashMap<String,Object>();
        InputStream res = null ;
        // 連線取得資料
        res = URLConnectionUtil.doGet(urlStr, true, wid.JENKINS_USR, wid.JENKINS_PWD, map);
		SAXReader reader = new SAXReader();
		document = reader.read(res);
		//Document document = reader.read(new File("C:\\Users\\Arthur\\Dropbox\\Arthur\\wsElegance\\client_demo\\src\\main\\java\\org\\jvnet\\hudson\\client_demo\\config.xml"));
		Element root = document.getRootElement();

		@SuppressWarnings("unchecked")
		Iterator<Element> it = root.elementIterator();

		while (it.hasNext()) {
			Element e2 = it.next();
			
			
			if ( "publishers".equalsIgnoreCase(e2.getName() ) ){
				if( e2.elementIterator().hasNext() ){
					Element e3 = e2.element("hudson.tasks.BuildTrigger");
					System.out.println("有下一個要Build的，它是"+e3.element("childProjects").getText());
					System.out.println("現在要刪掉它");
					
					root.element("publishers").remove(e3);
					
				} else {
					System.out.println("沒有下一個要建置的");
					System.out.println("現在要新增它");
					
					root.element("publishers").addElement("hudson.tasks.BuildTrigger").addElement("childProjects").setText("DPP");
					root.element("publishers").element("hudson.tasks.BuildTrigger").addElement("threshold");
					root.element("publishers").element("hudson.tasks.BuildTrigger").element("threshold").addElement("name").setText("SUCCESS");
					root.element("publishers").element("hudson.tasks.BuildTrigger").element("threshold").addElement("oridinal").setText("0");
					root.element("publishers").element("hudson.tasks.BuildTrigger").element("threshold").addElement("color").setText("BLUE");
				}
				
				PostMethod postMethod = new PostMethod(urlStr);
				postMethod.setRequestHeader("Content-type","application/xml; charset=UTF-8");
				postMethod.setRequestBody(new FileInputStream( saveToFile(new File("tmp"+System.currentTimeMillis()+".xml")) ));
				
				HttpClient client = new HttpClient();
				client.getParams().setAuthenticationPreemptive(true);
				client.getState().setCredentials( AuthScope.ANY, new UsernamePasswordCredentials("arthymoment", "arthymoment") );

				client.executeMethod(postMethod);
				
			}
		}

	}

	public static File saveToFile(File storedFile) {
		if (storedFile.exists())
			storedFile.delete();

		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		XMLWriter writer = null;
		try {
			storedFile.createNewFile();

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			fos = new FileOutputStream(storedFile);
			osw = new OutputStreamWriter(fos, Charset.forName("utf-8"));
			writer = new XMLWriter(osw, format);
			writer.write(document);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) writer.close();
				if (osw != null) osw.close();
				if (fos != null) fos.close();
			} catch (IOException e) {
			}
		}
		return storedFile;
	}

}
